package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class FileManager {

	private List<String> filesDir;

	public FileManager() {

	}

	public List<String> readTransformation(File file) throws IOException {
		FileReader fr = new FileReader(file);
		BufferedReader bf = new BufferedReader(fr);
		LinkedList<String> contentTransformation = new LinkedList<String>();
		String lineCode = bf.readLine();
		while (lineCode != null) {
			contentTransformation.add(lineCode.replace(" ", ""));
			lineCode = bf.readLine();
		}
		return contentTransformation;
	}

	private void getTransformationsPath(File dir) {
		File[] dirs = dir.listFiles();
		if (dirs.length == 0) {
			return;
		} else {
			for (File dirAux : dirs) {
				if (dirAux.getName().endsWith(".svn") || !dirAux.isDirectory()) {
					continue;
				}
				filesDir.add(dirAux.getAbsolutePath());
				getTransformationsPath(dirAux);
			}
		}

	}

	public File[] getTransformationsFiles(String path, String extension)
			throws IOException {
		File dirs = new File(path);
		getTransformationsPath(dirs);
		FilenameFilter selectM2TModel = new FileListFilter("", extension);
		File[] transformations = dirs.listFiles(selectM2TModel);
		// File[] transformations = dirs.listFiles();
		return transformations;

	}

	class FileListFilter implements FilenameFilter {
		private String name;
		private String extension;

		public FileListFilter(String name, String extension) {
			this.name = name;
			this.extension = extension;
		}

		public boolean accept(File directory, String filename) {
			boolean fileOK = true;

			if (name != null) {
				fileOK &= filename.startsWith(name);
			}
			if (extension != null) {
				fileOK &= filename.endsWith('.' + extension);
			}
			return fileOK;
		}
	}

}
